import os
import yaml

from utils.project_path import config


class YamlConfigUtils():

    def __init__(self):

        self.__application_data = {}

    def read_yaml(self, file_path):

        if not os.path.exists(file_path):
            raise FileNotFoundError("%s 文件不存在！" % file_path)
        with open(file_path, encoding='utf-8') as f:
            self.data = yaml.safe_load(f)
        return self.data

    def read_application_config(self, file_name):

        if self.__application_data is not None and len(self.__application_data) == 0:
            yaml_config_path = os.path.join(config.BASE_DIR, file_name)
            data = self.read_yaml(yaml_config_path)

            self.__application_data['host'] = data['host'][data['env']]
            self.__application_data['port'] = data['port'][data['env']]
            self.__application_data['headers'] = data['headers']
            self.__application_data['dbconfig'] = data['dbconfig']
        return self.__application_data

    def clear_application_data(self):

        self.__application_data = {}


yaml_config = YamlConfigUtils()
